// pages/habits/habits.js
Page({
  data: {
    inputValue: '',
    habitsList: [],
    showAddDialog: false,
    currentDate: ''
  },

  onLoad: function () {
    const today = new Date().toLocaleDateString()
    this.setData({
      currentDate: today
    })
    this.loadHabitsData()
  },

  onShow: function () {
    // 每次显示页面时重新加载数据
    this.loadHabitsData()
  },

  // 从本地存储加载习惯数据
  loadHabitsData: function() {
    const habitsList = wx.getStorageSync('habitsList') || []
    this.setData({
      habitsList: habitsList
    })
  },

  // 输入框内容变化
  onInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  // 显示添加习惯弹窗
  showAddDialog: function() {
    this.setData({
      showAddDialog: true
    })
  },

  // 隐藏添加习惯弹窗
  hideAddDialog: function() {
    this.setData({
      showAddDialog: false,
      inputValue: ''
    })
  },

  // 添加习惯
  addHabit: function() {
    if (!this.data.inputValue.trim()) {
      wx.showToast({
        title: '习惯名称不能为空',
        icon: 'none'
      })
      return
    }

    const today = new Date().toLocaleDateString()
    const newHabit = {
      id: Date.now(),
      name: this.data.inputValue.trim(),
      createDate: today,
      streak: 0,
      longestStreak: 0,
      completedDates: [],
      lastCompletedDate: ''
    }

    const habitsList = [newHabit, ...this.data.habitsList]
    this.setData({
      habitsList: habitsList,
      showAddDialog: false,
      inputValue: ''
    })

    // 保存到本地存储
    wx.setStorageSync('habitsList', habitsList)

    wx.showToast({
      title: '习惯创建成功',
      icon: 'success',
      duration: 1000
    })
  },

  // 切换习惯完成状态
  toggleHabitComplete: function(e) {
    const { id } = e.currentTarget.dataset
    const habitsList = [...this.data.habitsList]
    const habitIndex = habitsList.findIndex(item => item.id === id)
    
    if (habitIndex !== -1) {
      const habit = habitsList[habitIndex]
      const today = new Date().toLocaleDateString()
      const dateIndex = habit.completedDates.indexOf(today)
      
      if (dateIndex === -1) {
        // 标记今天完成
        habit.completedDates.push(today)
        habit.lastCompletedDate = today
        habit.streak++
        
        // 更新最长连续天数
        if (habit.streak > habit.longestStreak) {
          habit.longestStreak = habit.streak
        }
        
        wx.showToast({
          title: '太棒了，继续保持！',
          icon: 'success',
          duration: 1000
        })
      } else {
        // 取消完成标记
        habit.completedDates.splice(dateIndex, 1)
        
        // 重新计算连续天数
        this.recalculateStreak(habit)
        
        wx.showToast({
          title: '已取消标记',
          icon: 'none',
          duration: 1000
        })
      }
      
      this.setData({
        habitsList: habitsList
      })
      
      // 保存到本地存储
      wx.setStorageSync('habitsList', habitsList)
    }
  },

  // 重新计算连续天数
  recalculateStreak: function(habit) {
    if (habit.completedDates.length === 0) {
      habit.streak = 0
      habit.lastCompletedDate = ''
      return
    }
    
    // 按日期排序
    const sortedDates = [...habit.completedDates].sort((a, b) => new Date(b) - new Date(a))
    
    let currentStreak = 0
    let lastDate = new Date()
    
    for (let i = 0; i < sortedDates.length; i++) {
      let date = new Date(sortedDates[i])
      const diffTime = Math.abs(lastDate - date)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays <= 1 || i === 0) {
        currentStreak++
        lastDate = date
      } else {
        break
      }
    }
    
    habit.streak = currentStreak
    habit.lastCompletedDate = sortedDates[0]
  },

  // 删除习惯
  deleteHabit: function(e) {
    const { id } = e.currentTarget.dataset
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个习惯吗？所有记录将被清除。',
      success: res => {
        if (res.confirm) {
          const habitsList = this.data.habitsList.filter(item => item.id !== id)
          this.setData({
            habitsList: habitsList
          })
          // 保存到本地存储
          wx.setStorageSync('habitsList', habitsList)
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },

  // 查看习惯详情
  viewHabitDetail: function(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/habit-detail/habit-detail?id=${id}`
    })
  }
})